package org.example.booksmanagementsystem.redissync;

import lombok.extern.slf4j.Slf4j;
import org.example.booksmanagementsystem.mapper.RedisMapper;
import org.example.booksmanagementsystem.model.BookInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
public class DataSyncService {

    @Autowired
    private RedisMapper redisMapper;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    // 同步MySQL数据到Redis的核心方法
    public void syncMysqlToRedis() {
        log.info("开始同步MySQL数据到Redis...");
        long startTime = System.currentTimeMillis();

        try {
            // 1.从MySQL查询数据 book_info表
            List<BookInfo> bookInfoList = redisMapper.getBookInfoList();

            if (bookInfoList==null) {
                log.info("MySQL中无数据可同步");
            }

            // 2. 批量存入Redis
            for(BookInfo bookInfo : bookInfoList) {
                String id = "bookInfoId:" + bookInfo.getId();
                redisTemplate.opsForValue().set(id,bookInfo);
            }


            long endTime = System.currentTimeMillis();
            log.info("数据同步完成，共同步{}条数据，耗时{}ms", bookInfoList.size(), endTime - startTime);

        } catch (Exception e) {
            log.error("数据同步失败", e);
            throw new RuntimeException("Redis数据预加载失败", e);
        }
    }
}
